package com.cdht.util;

import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AesUtils {

    /**
     * 生成key
     * @return
     */
    public static String createKey() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
    }

    /**
     * 加密
     * @param key
     * @param data
     * @return
     */
    public static String encode(String key ,String JsonData) {
        
        try {
            // 确定算法
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES")); 
            // 不进行Base64编码的话，那么这个字节数组对应的字符串就是乱码
            byte[] result = cipher.doFinal(JsonData.getBytes()); 
            return Base64Util.encode(result).replaceAll(System.lineSeparator(), "").replaceAll(" ", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 解密
     * @param key
     * @param data
     * @return
     */
    public static String decode(String key,String data ) {
        try {
            data = data.replaceAll(System.lineSeparator(), "").replaceAll(" ", "");
            // 确定算法
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
            String result = StringUtils.toString(cipher.doFinal(Base64Util.decode(data)));
            return  result;
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return key;
    }
    

     public static void main(String[] args) {
        String key = AesUtils.createKey();
        System.out.println("ase key:"+key);  
        String data = "222";
        System.out.println("原文："+data);
        String enData = AesUtils.encode(key, data);
        System.out.println("ase 加密内容："+enData);
        String deData = AesUtils.decode(key, enData);
        System.out.println("ase 解密内容："+deData);
    }

}
